package com.eshealthy.utils;

import com.eshealthy.entity.Library;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class EsLibrary {
    public static void addLibrary(Library library) throws IOException {
        HttpHost host=new HttpHost("192.168.127.128",9200,"http");
        //创建es的客户端
        RestClientBuilder restClientBuilder= RestClient.builder(host);
        //获取 elasticsearch-rest-high-level-client
        RestHighLevelClient esClient=new RestHighLevelClient(restClientBuilder);
        IndexRequest indexRequest = new IndexRequest("library");
        CountRequest countRequest=new CountRequest("library");
        CountResponse count = esClient.count(countRequest, RequestOptions.DEFAULT);
        String id=String.valueOf(count.getCount()+1);
        //设置文档ID,不设置则系统生成
        indexRequest.id(id);
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("id", count.getCount()+1);
        jsonMap.put("name", library.getName());
        jsonMap.put("directions", library.getDirections());
        jsonMap.put("advice", library.getAdvice());
        indexRequest.source(jsonMap);
        IndexResponse index = esClient.index(indexRequest ,RequestOptions.DEFAULT);
        System.out.println(index);
    }
}
